package com.winit.openapi.controller;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alibaba.dubbo.common.utils.StringUtils;
import com.alibaba.fastjson.JSONObject;
import com.winit.common.query.Page;
import com.winit.common.query.SearchOperator;
import com.winit.common.query.Searchable;
import com.winit.common.query.Sort;
import com.winit.common.query.Sort.Direction;
import com.winit.common.query.filter.SearchFilterHelper;
import com.winit.common.spi.context.CommandContext;
import com.winit.common.utils.Collections3;
import com.winit.erp.spi.bpartner.vo.Bpartner;
import com.winit.erp.spi.warehouse.WarehouseService;
import com.winit.erp.spi.warehouse.command.WarehouseCommand;
import com.winit.erp.spi.warehouse.vo.Warehouse;
import com.winit.openapi.constants.ApiConstant;
import com.winit.openapi.constants.EnumConstant;
import com.winit.openapi.constants.ErrorCode;
import com.winit.openapi.exception.ApiException;
import com.winit.openapi.model.RequestMsg;
import com.winit.openapi.model.ResponseMsg;
import com.winit.openapi.util.ValidateUtil;
import com.winit.pms.spi.v2.base.BaseVasRelService;
import com.winit.pms.spi.v2.base.command.BaseVasRelQueryCommand;
import com.winit.pms.spi.v2.base.vo.BaseVasRelVo;
import com.winit.pms.spi.v2.base.vo.PlanEventVo;
import com.winit.pms.spi.v2.common.PmsConstants;
import com.winit.pms.spi.v2.common.PmsEnumType;
import com.winit.pms.spi.v2.instance.pscInstance.ProductInstanceService;
import com.winit.pms.spi.v2.instance.pscInstance.command.ProductInstanceCommand;
import com.winit.pms.spi.v2.instance.pscInstance.command.ProductLogisticsCommand;
import com.winit.pms.spi.v2.instance.pscInstance.command.ProductQueryCommand;
import com.winit.pms.spi.v2.instance.pscInstance.vo.ProductInstance;
import com.winit.pms.spi.v2.instance.pscInstance.vo.ProductLogisticsDist;
import com.winit.pms.spi.winit.LogisticsdistService;
import com.winit.pms.spi.winit.WinitDeliveryWayService;
import com.winit.pms.spi.winit.WinitPostService;
import com.winit.pms.spi.winit.WinitProductItemService;
import com.winit.pms.spi.winit.WinitProductService;
import com.winit.pms.spi.winit.WinitRuleService;
import com.winit.pms.spi.winit.WinitSlaService;
import com.winit.pms.spi.winit.command.LogisticsDistFindCommand;
import com.winit.pms.spi.winit.command.LogisticsQueryCommand;
import com.winit.pms.spi.winit.command.QueryWarehouseLogisticsDistCommand;
import com.winit.pms.spi.winit.command.ValidWinitSlaQueryCommand;
import com.winit.pms.spi.winit.command.WinitPostFindCommand;
import com.winit.pms.spi.winit.command.WinitProductFindCommand;
import com.winit.pms.spi.winit.command.WinitProductQueryBySellerCommand;
import com.winit.pms.spi.winit.command.WinitProductQueryCommand;
import com.winit.pms.spi.winit.command.WinitSlaFindCommand;
import com.winit.pms.spi.winit.vo.LogisticsDist;
import com.winit.pms.spi.winit.vo.WinitDeliveryWay;
import com.winit.pms.spi.winit.vo.WinitPost;
import com.winit.pms.spi.winit.vo.WinitProduct;
import com.winit.pms.spi.winit.vo.WinitSla;
import com.winit.tms.spi.common.TMSConstants;
import com.winit.ups.spi.command.CodeCommand;
import com.winit.ups.spi.warehouse.vo.WarehouseVo;

/**
 * Winit产品查询
 * 
 * @version Revision History
 * 
 * <pre>
 * Author     Version       Date        Changes
 * long.yue    1.0           2015年1月8日     Created
 * </pre>
 * @since 1.
 */
@Controller
@RequestMapping(value = "/winitProduct")
public class WinitProductController extends BaseController {

    private Logger                                       logger = LoggerFactory.getLogger(WinitProductController.class);

    @Resource
    private WinitProductService                          productService;

    @Resource
    private WarehouseService                             warehouseService;

    @Resource
    private WinitSlaService                              winitSlaService;

    @Resource
    private LogisticsdistService                         logisticsdistService;

    @Resource
    private WinitPostService                             winitPostService;

    @Resource
    private WinitRuleService                             winitRuleService;

    @Resource
    private WinitDeliveryWayService                      winitDeliveryWayService;

    @Resource
    private ProductInstanceService                       productInstanceService;
    @Resource
    private com.winit.ups.spi.warehouse.WarehouseService upsWarehouseService;
    @Resource
    private WinitProductItemService                      winitProductItemService;
    @Resource
    private BaseVasRelService                            baseVasRelService;

    public void setProductService(WinitProductService productService) {
        this.productService = productService;
    }

    private static Map<String, String> AssemblyTypeMap = new HashMap<String, String>();
    static {
        AssemblyTypeMap.put("FCL", "SEA");
        AssemblyTypeMap.put("LCL", "SEA");
        AssemblyTypeMap.put("AF", "AIR");
        AssemblyTypeMap.put("AFB", "AIR");
        AssemblyTypeMap.put("FTL", "ROAD");
        AssemblyTypeMap.put("LTL", "ROAD");
    }

    @RequestMapping(value = "/list")
    public String list(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg) {
        List<Map<String, String>> dataList = new ArrayList<Map<String, String>>();
        // 获取参数
        JSONObject json = JSONObject.parseObject(requestMsg.getData() == null ? "" : requestMsg.getData().toString());
        if (json != null && json.containsKey("warehouseID") && !StringUtils.isBlank(json.getString("warehouseID"))) {
            Long warehouseID = Long.parseLong(json.getString("warehouseID"));
            // 根据Id获取仓库
            Warehouse warehouse = getWarehouse(warehouseID);
            // 根据邮编获取物流分区
            List<Long> logisticsIdList = getLogisticsIdList(warehouse.getPostal());
            // 过滤非仓库的物流分区
            logisticsIdList = getWHLogisticsIdList(logisticsIdList);
            if (logisticsIdList.size() > 0) {
                // 获取产品Id列表
                List<Long> productIdList = getWinitProductIdList(logisticsIdList);
                if (productIdList.size() > 0) {
                    WinitProductFindCommand productCommand = new WinitProductFindCommand();
                    Searchable searchable = Searchable.newSearchable();
                    // 查询所有的值
                    searchable.setPage(0, Integer.MAX_VALUE);
                    // 按组织ID查询
                    searchable.and(SearchFilterHelper.newCondition("ORGANIZATION_ID",
                        SearchOperator.eq,
                        CommandContext.getContext().getOrgId()));
                    searchable.and(SearchFilterHelper.newCondition("WINIT_PRODUCT_ID",
                        SearchOperator.in,
                        convertIn(productIdList)));
                    productCommand.setSearchable(searchable);
                    Page<WinitProduct> page = productService.findProduct(productCommand);
                    if (null != page && page.getContent() != null && page.getContent().size() > 0) {
                        for (WinitProduct product : page.getContent()) {
                            Map<String, String> r1 = new HashMap<String, String>();
                            r1.put("productCode", product.getCode());
                            r1.put("productName", product.getName());
                            r1.put("description", product.getDescription());
                            r1.put("isSelfInspection", product.getIsSelfInspection());
                            r1.put("isClaim", product.getIsClaim());
                            dataList.add(r1);
                        }
                    }
                }
            }
        } else {
            WinitProductQueryBySellerCommand command = new WinitProductQueryBySellerCommand();
            command.setCtx(CommandContext.getContext());
            // TODO lihui update 修改查询入库产品列表默认组织1000000
            command.setOrganizationId(1000000L);
            // 产品分类名称
            if (null != json && ValidateUtil.isNotNull(json, "productCatalogName")) {
                command.setProductCatelogName(json.getString("productCatalogName"));
            } else {
                // 之前默认类型为ISP
                command.setProductCatelogName(ApiConstant.PRODUCT_CATALOG_ISP);
            }
            if ("OW01".equals(command.getProductCatelogName()) || "SSW1".equals(command.getProductCatelogName())) {
                WinitProductFindCommand productCommand = new WinitProductFindCommand();
                Searchable searchable = Searchable.newSearchable();
                // 查询所有的值
                searchable.setPage(0, Integer.MAX_VALUE);
                // 按组织ID查询
                // TODO lihui update 修改查询入库产品列表默认组织1000000
                searchable.and(SearchFilterHelper.newCondition("ORGANIZATION_ID", SearchOperator.eq, 1000000));
                searchable.and(SearchFilterHelper.newCondition("PRODUCT_CATALOG_NAME",
                    SearchOperator.like,
                    command.getProductCatelogName() + "%"));
                searchable.and(SearchFilterHelper.newCondition("IS_ACTIVE", SearchOperator.eq, "Y"));
                productCommand.setSearchable(searchable);
                Page<WinitProduct> page = productService.findProduct(productCommand);
                if (null != page && page.getContent() != null && page.getContent().size() > 0) {
                    for (WinitProduct product : page.getContent()) {
                        Map<String, String> r1 = new HashMap<String, String>();
                        r1.put("productCode", product.getCode());
                        r1.put("productName", product.getName());
                        r1.put("description", product.getDescription());
                        r1.put("isSelfInspection", product.getIsSelfInspection());
                        r1.put("isClaim", product.getIsClaim());
                        dataList.add(r1);
                    }
                }
            } else if (PmsConstants.PRODUCT_CATEGORY_OSF8.equals(command.getProductCatelogName())
                       || PmsConstants.PRODUCT_CATEGORY_OSF7.equals(command.getProductCatelogName())
                       || PmsConstants.PRODUCT_CATEGORY_SSW31.equals(command.getProductCatelogName())
                       || PmsConstants.PRODUCT_CATEGORY_SSW32.equals(command.getProductCatelogName())) {// 出库
                ProductQueryCommand queryCommand = new ProductQueryCommand();
                queryCommand.setCtx(CommandContext.getContext());
                queryCommand.setTwoCategoryCode(command.getProductCatelogName());
                Bpartner bpartner = CommandContext.getContext().get(ApiConstant.API_BPARTNER);
                if (bpartner != null) {
                    queryCommand.setBpartnerCode(bpartner.getValue());
                } else {
                    queryCommand.setBpartnerCode(CommandContext.getContext().getUserId());
                }
                List<ProductInstance> productList = productInstanceService.queryProductBaseInfoList(queryCommand);
                if (null != productList && productList.size() > 0) {
                    for (ProductInstance product : productList) {
                        Map<String, String> r1 = new HashMap<String, String>();
                        r1.put("productCode", product.getCode());
                        r1.put("productName", product.getName());
                        r1.put("description", product.getDescription());
                        r1.put("categoryCode", product.getCategoryCode());
                        dataList.add(r1);
                    }
                }
            } else {
                if (null != json && ValidateUtil.isNotNull(json, "productCatalogLv2")) {
                    command.setProductCatalogLv2(json.getString("productCatalogLv2"));
                }
                List<WinitProduct> productList = productService.queryWinitProduct(command);
                if (null != productList && productList.size() > 0) {
                    for (WinitProduct product : productList) {
                        Map<String, String> r1 = new HashMap<String, String>();
                        r1.put("productCode", product.getCode());
                        r1.put("productName", product.getName());
                        r1.put("description", product.getDescription());
                        r1.put("isSelfInspection", product.getIsSelfInspection());
                        r1.put("isClaim", product.getIsClaim());
                        r1.put("productCatalogLv2", product.getProductCatalogLv2());
                        dataList.add(r1);
                    }
                }
            }
        }
        responseMsg.setData(dataList);
        return SUCCESS;
    }

    /**
     * 根据仓库Id查询仓库
     * 
     * @param warehouseId
     * @return
     */
    private Warehouse getWarehouse(Long warehouseId) {
        // 初始化查询command
        WarehouseCommand command = new WarehouseCommand();
        command.setWarehouseId(warehouseId);
        // 查询仓库信息
        Warehouse warehouse = warehouseService.getWarehouse(command);
        return warehouse;
    }

    /**
     * 根据邮编查询满足条件的物流分区ID
     * 
     * @param postcode
     * @return
     */
    private List<Long> getLogisticsIdList(String postcode) {
        WinitPostFindCommand command = new WinitPostFindCommand();
        // 初始化查询条件seachable
        Searchable searchable = Searchable.newSearchable();
        searchable.and(SearchFilterHelper.newCondition("CODE", SearchOperator.eq, postcode));
        // 查询所有满足条件的数据
        searchable.setPage(0, Integer.MAX_VALUE);
        command.setSearchable(searchable);
        Page<WinitPost> page = winitPostService.findWinitPost(command);
        List<Long> logisticsIdList = new ArrayList<Long>();
        if (null != page && null != page.getContent() && page.getContent().size() > 0) {
            for (WinitPost post : page.getContent()) {
                if (!logisticsIdList.contains(post.getWinitLogisticsdistId())) {
                    logisticsIdList.add(post.getWinitLogisticsdistId());
                }
            }
        }
        return logisticsIdList;
    }

    /**
     * 获取仓库的物流分区
     * 
     * @param logisticsIdList
     * @return
     */
    private List<Long> getWHLogisticsIdList(List<Long> logisticsIdList) {
        List<Long> list = new ArrayList<Long>();
        for (Long id : logisticsIdList) {
            LogisticsDistFindCommand command = new LogisticsDistFindCommand();
            // 初始化查询条件seachable
            Searchable searchable = Searchable.newSearchable();
            searchable.and(SearchFilterHelper.newCondition("WINIT_LOGISTICSDIST_ID", SearchOperator.eq, id));
            // 根据ID查询，结果唯一
            searchable.setPage(0, 1);
            searchable.addSort(new Sort(Direction.DESC, "WINIT_LOGISTICSDIST_ID"));
            command.setSearchable(searchable);
            command.setCtx(CommandContext.getContext());
            Page<LogisticsDist> page = logisticsdistService.findLogisticsDist(command);
            if (null != page && null != page.getContent() && page.getContent().size() > 0) {
                LogisticsDist logisticsDist = page.getContent().get(0);
                if (null != logisticsDist && "Warehouse".equals(logisticsDist.getDistrictType())) {
                    list.add(logisticsDist.getWinitLogisticsdistId());
                } else {
                    logger.info("万邑通产品物流分区不为仓库分区, id:{}", new Object[] { id });
                }
            } else {
                logger.info("万邑通产品物流分区不存在, id:{}", new Object[] { id });
            }
        }
        return list;
    }

    /**
     * 根据物流分区Id获取产品Id
     * 
     * @param logisticsIdList
     * @return
     */
    private List<Long> getWinitProductIdList(List<Long> logisticsIdList) {
        WinitSlaFindCommand command = new WinitSlaFindCommand();
        Searchable searchable = Searchable.newSearchable();
        searchable.and(SearchFilterHelper.newCondition("SLA_BEGIAN", SearchOperator.in, convertIn(logisticsIdList)));
        // 查询所有数据
        searchable.setPage(0, Integer.MAX_VALUE);
        command.setSearchable(searchable);
        Page<WinitSla> page = winitSlaService.findWinitSla(command);
        List<Long> ProductIdList = new ArrayList<Long>();
        if (null != page && null != page.getContent() && page.getContent().size() > 0) {
            for (WinitSla sla : page.getContent()) {
                if (!ProductIdList.contains(sla.getWinitProductId())) {
                    ProductIdList.add(sla.getWinitProductId());
                }
            }
        }
        return ProductIdList;
    }

    /**
     * 拼接查询in条件
     * 
     * @param slaList
     * @return
     */
    private String convertIn(List<Long> slaList) {
        StringBuffer buff = new StringBuffer();
        boolean startFlag = true;
        for (Long logisticId : slaList) {
            if (startFlag) {
                buff.append("(").append(logisticId);
                startFlag = false;
            } else {
                buff.append(",").append(logisticId);
            }
        }
        buff.append(")");
        return buff.toString();
    }

    /**
     * 根据条件查询仓库列表
     * 
     * @param 验货仓类型值：Warehouse
     * @param 目的仓类型值：DestWarehouse
     * @param requestMsg
     * @param responseMsg
     * @return
     * @throws ParseException
     */
    @RequestMapping(value = "/queryWarehouseList")
    public String queryWarehouseList(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg)
                                                                                                                    throws ParseException {
        Object obj = requestMsg.getData();
        QueryWarehouseLogisticsDistCommand command = new QueryWarehouseLogisticsDistCommand();
        String inspWarehouseCode = null;
        if (obj instanceof JSONObject) {
            JSONObject json = (JSONObject) obj;
            if (json.containsKey("productCode")) {
                command.setProductCode(json.getString("productCode"));
            }
            if (json.containsKey("distType")) {
                command.setDistType(json.getString("distType"));
            }
            if (json.containsKey("warehouseCode")) {
                inspWarehouseCode = json.getString("warehouseCode");
            }
        } else {
            throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "data");
        }
        List<LogisticsDist> distList = logisticsdistService.queryWarehouseList(command);
        Map<String, String> warehouseMap = null;
        if (distList != null && distList.size() > 0) {
            warehouseMap = new HashMap<String, String>();
            if ("Warehouse".equals(command.getDistType())) {// 查询验货仓列表
                for (LogisticsDist dist : distList) {
                    warehouseMap.put(dist.getCode(), dist.getName());
                }
            } else {// 根据验货仓查询目的仓列表
                WinitProductQueryCommand productCommand = new WinitProductQueryCommand();
                productCommand.setCode(command.getProductCode());
                WinitProduct product = productService.queryProduct(productCommand);
                if (null != product) {
                    ValidWinitSlaQueryCommand slaCommand = new ValidWinitSlaQueryCommand();
                    slaCommand.setWinitProductId(product.getWinitProductId());
                    List<WinitSla> slaList = winitSlaService.queryValidWinitSlaByPorductId(slaCommand);
                    if (StringUtils.isBlank(inspWarehouseCode)) {
                        if (null != slaList && slaList.size() > 0) {
                            for (LogisticsDist dist : distList) {
                                for (WinitSla sla : slaList) {
                                    if (dist.getWinitLogisticsdistId().longValue() == sla.getSlaEnd().longValue()) {
                                        warehouseMap.put(dist.getCode(), dist.getName());
                                    }
                                }
                            }
                        }
                    } else {
                        Long inspWarehouseDistId = this.getLogisticsDistId(product.getWinitProductId(),
                            inspWarehouseCode);
                        if (null != slaList && slaList.size() > 0 && null != inspWarehouseDistId) {
                            for (LogisticsDist dist : distList) {
                                for (WinitSla sla : slaList) {
                                    if (inspWarehouseDistId.longValue() == sla.getSlaBegian().longValue()
                                        && dist.getWinitLogisticsdistId().longValue() == sla.getSlaEnd().longValue()) {
                                        warehouseMap.put(dist.getCode(), dist.getName());
                                    }
                                }
                            }
                        }
                    }
                } else {
                    for (LogisticsDist dist : distList) {
                        warehouseMap.put(dist.getCode(), dist.getName());
                    }
                }
            }
        }

        responseMsg.setData(warehouseMap);

        return SUCCESS;
    }

    /**
     * 获取验货仓类型物流分区ID
     * 
     * @param winitProductId
     * @return
     */
    private Long getLogisticsDistId(Long winitProductId, String inspWarehouseCode) {
        LogisticsQueryCommand command = new LogisticsQueryCommand();
        command.setWinitProductId(winitProductId);
        List<LogisticsDist> distList = logisticsdistService.queryWinitLogisticsDistByPorductId(command);
        if (null != distList && distList.size() > 0) {
            for (LogisticsDist dist : distList) {
                if ("Warehouse".equals(dist.getDistrictType()) && inspWarehouseCode.equals(dist.getCode())) {
                    return dist.getWinitLogisticsdistId();
                }
            }
        }
        return null;
    }

    /**
     * 根据条件查询验货仓库列表
     * 
     * @param 验货仓类型值：Warehouse
     * @param 目的仓类型值：DestWarehouse
     * @param requestMsg
     * @param responseMsg
     * @return
     * @throws ParseException
     */
    @RequestMapping(value = "/getInspectionWarehouseList")
    public String getInspectionWarehouseList(@ModelAttribute RequestMsg requestMsg,
                                             @ModelAttribute ResponseMsg responseMsg) throws ParseException {
        Object obj = requestMsg.getData();
        QueryWarehouseLogisticsDistCommand command = new QueryWarehouseLogisticsDistCommand();
        if (obj instanceof JSONObject) {
            JSONObject json = (JSONObject) obj;
            if (json.containsKey("winitProductCode")) {
                command.setProductCode(json.getString("winitProductCode"));
            }
            command.setDistType("Warehouse");
        } else {
            throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "data");
        }
        List<LogisticsDist> distList = logisticsdistService.queryWarehouseList(command);
        Map<String, String> warehouseMap = null;
        if (distList != null && distList.size() > 0) {
            warehouseMap = new HashMap<String, String>();
            for (LogisticsDist dist : distList) {
                warehouseMap.put(dist.getCode(), dist.getName());
            }
        }

        responseMsg.setData(warehouseMap);

        return SUCCESS;
    }

    /**
     * 根据条件查询目的仓库列表
     * 
     * @param 验货仓类型值：Warehouse
     * @param 目的仓类型值：DestWarehouse
     * @param requestMsg
     * @param responseMsg
     * @return
     * @throws ParseException
     */
    @RequestMapping(value = "/getDestinationWarehouseList")
    public String getDestinationWarehouseList(@ModelAttribute RequestMsg requestMsg,
                                              @ModelAttribute ResponseMsg responseMsg) throws ParseException {
        Object obj = requestMsg.getData();
        QueryWarehouseLogisticsDistCommand command = new QueryWarehouseLogisticsDistCommand();
        if (obj instanceof JSONObject) {
            JSONObject json = (JSONObject) obj;
            if (json.containsKey("winitProductCode")) {
                command.setProductCode(json.getString("winitProductCode"));
            }
            command.setDistType("DestWarehouse");
        } else {
            throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "data");
        }
        List<LogisticsDist> distList = logisticsdistService.queryWarehouseList(command);
        Map<String, String> warehouseMap = null;
        if (distList != null && distList.size() > 0) {
            warehouseMap = new HashMap<String, String>();
            for (LogisticsDist dist : distList) {
                warehouseMap.put(dist.getCode(), dist.getName());
            }
        }

        responseMsg.setData(warehouseMap);

        return SUCCESS;
    }

    /**
     * 根据条件查询产品运输方式
     * 
     * @param productCode
     * @param requestMsg
     * @param responseMsg
     * @return
     * @throws ParseException
     */
    @RequestMapping(value = "/getTransportModeByProductCode")
    public String getTransportModeByProductCode(@ModelAttribute RequestMsg requestMsg,
                                                @ModelAttribute ResponseMsg responseMsg) throws ParseException {
        Object obj = requestMsg.getData();
        WinitProductQueryCommand command = new WinitProductQueryCommand();
        if (obj instanceof JSONObject) {
            JSONObject json = (JSONObject) obj;
            if (json.containsKey("productCode")) {
                command.setCode(json.getString("productCode"));
            }
        } else {
            throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "data");
        }

        Map<String, String> warehouseMap = new HashMap<String, String>();
        WinitProduct product = productService.queryProduct(command);
        if (null != product) {
            if (org.apache.commons.lang3.StringUtils.isNoneBlank(product.getAssemblyType())) {
                warehouseMap.put("transportMode", AssemblyTypeMap.get(product.getAssemblyType()));
            } else {
                throw new ApiException(ErrorCode.PRODUCT_LIMIT_ERROR, "data");
            }
        }
        responseMsg.setData(warehouseMap);
        return SUCCESS;
    }

    @RequestMapping(value = "/getDeliveryWay")
    public String getDeliveryWay(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg)
                                                                                                                throws ParseException {
        Object obj = requestMsg.getData();
        WinitProductQueryCommand command = new WinitProductQueryCommand();
        if (obj instanceof JSONObject) {
            JSONObject json = (JSONObject) obj;
            ValidateUtil.validNotNull(json, "productCode");
            command.setCode(json.getString("productCode"));
        } else {
            throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "data");
        }

        WinitProduct product = productService.queryProduct(command);
        if (null != product) {
            List<WinitDeliveryWay> datalist = winitDeliveryWayService.getWinitDeliveryWayListByProductId(product.getWinitProductId());
            Map<String, Object> data = new HashMap<String, Object>();
            data.put("list", datalist);
            responseMsg.setData(data);
        }
        return SUCCESS;
    }

    @RequestMapping(value = "/queryWinitProductList")
    public String queryWinitProductList(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg)
                                                                                                                       throws ParseException {
        Object obj = requestMsg.getData();
        ProductQueryCommand command = new ProductQueryCommand();
        if (obj instanceof JSONObject) {
            JSONObject json = (JSONObject) obj;
            ValidateUtil.validNotNull(json, "categoryCode");// 必填
            command.setCategoryCode(json.getString("categoryCode"));// 产品分类
            String inspWarehouseCode = json.getString("inspWarehouseCode");// 验货仓
            String inspWarehouseType = json.getString("inspWarehouseType");// 验货仓类型
            String destWarehouseCode = json.getString("destWarehouseCode");// 目的仓
            String destWarehouseType = json.getString("destWarehouseType");// 目的仓类型
            ProductLogisticsDist startDist = null;
            ProductLogisticsDist endDist = null;
            if (StringUtils.isNotEmpty(inspWarehouseCode) && StringUtils.isNotEmpty(inspWarehouseType)) {// 发货仓校验
                CodeCommand codeCommand = new CodeCommand();
                codeCommand.setCode(inspWarehouseCode);
                WarehouseVo warehouseVo = upsWarehouseService.queryWarehouseByCode(codeCommand);
                if (warehouseVo != null) {
                    startDist = new ProductLogisticsDist();
                    startDist.setLogisticsDistCode(inspWarehouseCode); // 仓库编码
                    startDist.setCountryCode(warehouseVo.getCountryCode());// 国家编码
                    startDist.setLogisticsDistType(inspWarehouseType);// 分区类型
                }

            }
            if (StringUtils.isNotEmpty(destWarehouseCode) && StringUtils.isNotEmpty(destWarehouseType)) {// 目的仓校验
                CodeCommand codeCommand = new CodeCommand();
                codeCommand.setCode(destWarehouseCode);
                WarehouseVo warehouseVo = upsWarehouseService.queryWarehouseByCode(codeCommand);
                if (warehouseVo != null) {
                    endDist = new ProductLogisticsDist();
                    endDist.setLogisticsDistCode(destWarehouseCode); // 仓库编码
                    endDist.setCountryCode(warehouseVo.getCountryCode());// 国家编码
                    endDist.setLogisticsDistType(destWarehouseType);// 分区类型
                }
            }
            command.setBeginDist(startDist);
            command.setEndDist(endDist);
            Bpartner bpartner = CommandContext.getContext().get(ApiConstant.API_BPARTNER);
            if (bpartner != null) {
                command.setBpartnerCode(bpartner.getValue());
            } else {
                command.setBpartnerCode(CommandContext.getContext().getUserId());
            }
            List<ProductInstance> datalist = productInstanceService.queryProductListByCategory(command);
            Map<String, Object> data = new HashMap<String, Object>();
            data.put("list", datalist);
            responseMsg.setData(data);// 返回产品列表数据
        } else {
            throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "data");
        }

        return SUCCESS;
    }

    /**
     * 根据产品编码查询产品以及运输方式编码
     */
    @RequestMapping(value = "/queryWinitProductByCode")
    public String queryWinitProductByCode(@ModelAttribute RequestMsg requestMsg, @ModelAttribute ResponseMsg responseMsg)
                                                                                                                         throws ParseException {
        Object obj = requestMsg.getData();
        WinitProductQueryCommand command = new WinitProductQueryCommand();
        if (obj instanceof JSONObject) {
            JSONObject json = (JSONObject) obj;
            if (json.containsKey("productCode")) {
                command.setCode(json.getString("productCode"));
            }
        }
        WinitProduct winitProduct = productService.queryProduct(command);
        if (null != winitProduct) {
            if (this.isContainLogisticsSu(command.getCode())) {
                winitProduct.setIsContainTransnationalTransportSu("Y");
            } else {
                winitProduct.setIsContainTransnationalTransportSu("N");
            }
        }
        responseMsg.setData(winitProduct);
        return SUCCESS;
    }

    /**
     * 判断产品是否包含跨国运输服务（空运、海运）
     * 
     * @param productCode
     * @return
     */
    private boolean isContainLogisticsSu(String productCode) {
        WinitProductQueryCommand suCommand = new WinitProductQueryCommand();
        suCommand.setCode(productCode);
        String transportCategory = null;
        try {
            List<WinitProduct> serviceList = winitProductItemService.queryServiceItemAllByProductIdOrCode(suCommand);
            // 找出服务里的运输方式 空运:C0301|C030102 海运:C0302|C030202 快递:C0303
            if (Collections3.isNotEmpty(serviceList)) {
                for (WinitProduct serviceUnit : serviceList) {
                    if (EnumConstant.ThirdLevelCategory.CATEGORY_TRANSPORT_AIR.getCode()
                        .equals(serviceUnit.getServiceCatalogCode())
                        || EnumConstant.ThirdLevelCategory.CATEGORY_TRANSPORT_AIR_V2.getCode()
                            .equals(serviceUnit.getServiceCatalogCode())) {
                        transportCategory = TMSConstants.KONGYUN_TYPE;
                        break;
                    } else if (EnumConstant.ThirdLevelCategory.CATEGORY_TRANSPORT_SEA.getCode()
                        .equals(serviceUnit.getServiceCatalogCode())
                               || EnumConstant.ThirdLevelCategory.CATEGORY_TRANSPORT_SEA_V2.getCode()
                                   .equals(serviceUnit.getServiceCatalogCode())) {
                        transportCategory = TMSConstants.HAIYUN_TYPE;
                        break;
                    } else if (EnumConstant.ThirdLevelCategory.CATEGORY_TRANSPORT_EXPRESS.getCode()
                        .equals(serviceUnit.getServiceCatalogCode())) {
                        transportCategory = TMSConstants.KUAIDI_TYPE;
                        break;
                    }
                }
            }
        } catch (Exception e) {
            logger.error("查询服务分类失败", e);
        }
        return TMSConstants.KONGYUN_TYPE.equals(transportCategory)
               || TMSConstants.HAIYUN_TYPE.equals(transportCategory);
    }

    @RequestMapping(value = "/queryOutboundProductList")
    public String queryOutboundProductList(@ModelAttribute RequestMsg requestMsg,
                                           @ModelAttribute ResponseMsg responseMsg) throws ParseException {
        Object obj = requestMsg.getData();
        ProductLogisticsCommand command = new ProductLogisticsCommand();
        if (obj instanceof JSONObject) {
            JSONObject json = (JSONObject) obj;
            ValidateUtil.validNotNull(json, "destWarehouseCode");// 必填
            String destWarehouseCode = json.getString("destWarehouseCode");// 目的仓
            com.winit.pms.spi.v2.vo.LogisticsDist endDist = null;
            if (StringUtils.isNotEmpty(destWarehouseCode)) {// 目的仓校验
                CodeCommand codeCommand = new CodeCommand();
                codeCommand.setCode(destWarehouseCode);
                WarehouseVo warehouseVo = upsWarehouseService.queryWarehouseByCode(codeCommand);
                if (warehouseVo != null) {
                    endDist = new com.winit.pms.spi.v2.vo.LogisticsDist();
                    endDist.setLogisticsDistCode(destWarehouseCode); // 仓库编码
                    endDist.setCountryCode(warehouseVo.getCountryCode());// 国家编码
                    endDist.setLogisticsDistType(PmsEnumType.EnumDistrictType.FULFILLMENTWAREHOUSE.getType());// 分区类型
                }
            }
            command.setLocisticsDist(endDist);
            Bpartner bpartner = CommandContext.getContext().get(ApiConstant.API_BPARTNER);
            if (bpartner != null) {
                command.setCustomerCode(bpartner.getValue());
            } else {
                command.setCustomerCode(CommandContext.getContext().getUserId());
            }
            List<ProductInstance> datalist = productInstanceService.queryProductInstanceByLogistics(command);
            Map<String, Object> data = new HashMap<String, Object>();
            data.put("list", datalist);
            responseMsg.setData(data);// 返回产品列表数据
        } else {
            throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "data");
        }

        return SUCCESS;
    }

    @RequestMapping(value = "/queryPlanEventListByProductCode")
    public String queryPlanEventListByProductCode(@ModelAttribute RequestMsg requestMsg,
                                                  @ModelAttribute ResponseMsg responseMsg) throws ParseException {
        Object obj = requestMsg.getData();
        if (obj instanceof JSONObject) {
            JSONObject json = (JSONObject) obj;
            ValidateUtil.validNotNull(json, "winitProductCode");// 必填
            String winitProductCode = json.getString("winitProductCode");// 产品编码
            BaseVasRelQueryCommand command = new BaseVasRelQueryCommand();
            BaseVasRelVo vo = new BaseVasRelVo();
            vo.setInstanceCode(winitProductCode);
            vo.setType(PmsEnumType.BaseVasRelType.PSC_INSTANCE.getCode());
            vo.setIsActive(PmsConstants.ACTIVE_Y);
            command.setVo(vo);
            List<PlanEventVo> datalist = baseVasRelService.queryPlanEventListByProductCode(command);
            Map<String, Object> data = new HashMap<String, Object>();
            data.put("list", datalist);
            responseMsg.setData(data);// 返回产品列表数据
        } else {
            throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "data");
        }

        return SUCCESS;
    }

    @RequestMapping(value = "/queryPSCListByCategoryCode")
    public String queryPSCListByCategoryCode(@ModelAttribute RequestMsg requestMsg,
                                             @ModelAttribute ResponseMsg responseMsg) throws ParseException {
        Object obj = requestMsg.getData();
        if (obj instanceof JSONObject) {
            JSONObject json = (JSONObject) obj;
            ValidateUtil.validNotNull(json, "categoryCode");// 必填
            String categoryCode = json.getString("categoryCode");// 产品分类 编码
            ProductInstanceCommand command = new ProductInstanceCommand();
            ProductInstance product = new ProductInstance();
            product.setCategoryCode(categoryCode);
            command.setProduct(product);
            Map<String, String> data = productInstanceService.queryPSCList(command);
            responseMsg.setData(data);// 返回产品列表数据
        } else {
            throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "data");
        }

        return SUCCESS;
    }

    @RequestMapping(value = "/queryProductListByCategoryCode")
    public String queryProductListByCategoryCode(@ModelAttribute RequestMsg requestMsg,
                                                 @ModelAttribute ResponseMsg responseMsg) throws ParseException {
        Object obj = requestMsg.getData();
        if (obj instanceof JSONObject) {
            JSONObject json = (JSONObject) obj;
            ValidateUtil.validNotNull(json, "productLine");// 必填
            String productLine = json.getString("productLine");// 产品线
            String pscgCode = json.getString("pscgCode");// PSCG
            String subPscgCode = json.getString("subPscgCode");// subPscg
            String pscCode = json.getString("pscCode");// psc
            ProductQueryCommand command = new ProductQueryCommand();
            command.setOneCategoryCode(productLine);
            if (StringUtils.isNotEmpty(pscgCode)) {
                command.setTwoCategoryCode(pscgCode);
            }
            if (StringUtils.isNotEmpty(subPscgCode)) {
                command.setCategoryCode(subPscgCode);
            }
            if (StringUtils.isNotEmpty(pscCode)) {
                command.setPscCode(pscCode);
            }
            Bpartner bpartner = CommandContext.getContext().get(ApiConstant.API_BPARTNER);
            if (bpartner != null) {
                command.setBpartnerCode(bpartner.getValue());
            } else {
                command.setBpartnerCode(CommandContext.getContext().getUserId());
            }
            List<ProductInstance> productList = productInstanceService.queryProductListByCategoryCode(command);
            Map<String, Object> data = new HashMap<String, Object>();
            data.put("list", productList);
            responseMsg.setData(data);// 返回产品列表数据
        } else {
            throw new ApiException(ErrorCode.FIELD_TYPE_ERROR, "data");
        }

        return SUCCESS;
    }
}
